#include<iostream>
using namespace std;


struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
 
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int nodeDig = 0;
        ListNode* pcur = head;
        while (pcur != nullptr) {
            nodeDig++;
            pcur = pcur->next;
        }
        int posDel = nodeDig - n + 1;
        ListNode* root = new ListNode(-1, head);
        int posi = 0;
        pcur = root;
        while (posi + 1 < posDel) {
            posi++;
            pcur = pcur->next;
        }
        ListNode* nodedel = pcur->next;
        pcur->next = nodedel->next;
        delete nodedel;
        return root->next;
    }
};